import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
// import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (!config.headers.Authorization && store.state.user.token) {
      config.headers.Authorization = 'Bearer ' + store.state.user.token
    }
    // if (store.getters.token) {
    //   // let each request carry token
    //   // ['X-Token'] is a custom headers key
    //   // please modify it according to the actual situation
    //   config.headers['X-Token'] = getToken()
    // }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// // 响应拦截器
// service.interceptors.response.use(
//   response => {
//     // 处理接口返回状态码是200 但是请求失败的情况
//     // 解构接口返回值中的 data message success
//     // 根据success判断当前接口是否成功
//     // 如果success === true直接将接口返回值return
//     // 如果success === false 使用element组件 + message字段提示用户
//     const { msg, isSuccess } = response.data
//     if (isSuccess) {
//       Message.success(msg)
//       return response
//     } else {
//       Message.error(msg)
//       return Promise.reject(msg)
//     }
//   },
//   error => {
//     Message.error('未知错误')
//     return Promise.reject(error)
//   }
// )

export default service
